package com.atguigu.juc.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 如何停止中断运行中的线程？
 *
 * @author yfstart
 * @create 2022-06-30 19:34
 */
public class InterruptDemo {
  static volatile boolean isStop = false;
  static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

  public static void main(String[] args) {
    // volatileInterrupt();
    // atomicBooleanInterrupt();
    threadApiInterrupt();
  }

  private static void threadApiInterrupt() {
    Thread t1 = new Thread(() -> {
      while (true) {
        if (Thread.currentThread().isInterrupted()) {
          System.out.println(Thread.currentThread().getName() + "\t ---isInterrupted() 被修改为true，程序停止");
          break;
        }
        System.out.println("hello isInterrupted api");
      }
    }, "t1");
    t1.start();

    try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace();}

    new Thread(()->{
      t1.interrupt();
    },"t2").start();
  }

  private static void atomicBooleanInterrupt() {
    new Thread(()->{
      while (true){
        if (atomicBoolean.get()){
          System.out.println(Thread.currentThread().getName() + "\t ---atomicBoolean被修改为true，程序停止");
          break;
        }
        System.out.println("hello atomicBoolean");
      }
    },"t1").start();

    try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace();}

    new Thread(()->{
      atomicBoolean.set(true);
    },"t2").start();
  }

  private static void volatileInterrupt() {
    new Thread(()->{
      while (true){
        if (isStop){
          System.out.println(Thread.currentThread().getName() + "\t ---isStop被修改为true，程序停止");
          break;
        }
        System.out.println("hello volatile");
      }
    },"t1").start();

    try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace();}

    new Thread(()->{
        isStop = true;
    },"t2").start();
  }
}
